package com.example.demo.jpa.config.web;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;

@Component
public class UrlMappingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod handlerMethod){
            StringBuilder sb = new StringBuilder();
            Class<?> clazz=handlerMethod.getBeanType();
            RequestMapping classMapping=AnnotationUtils.findAnnotation(clazz, RequestMapping.class);
            sb.append(request.getMethod());
            sb.append(" ");
            if (Objects.nonNull(classMapping) && Objects.nonNull(classMapping.value())
                    && classMapping.value().length>0){
                sb.append(classMapping.value()[0]);
            }
            RequestMapping methodMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
            if (Objects.nonNull(methodMapping) && Objects.nonNull(methodMapping.value())
                    && methodMapping.value().length>0){
                sb.append(methodMapping.value()[0]);
            }
            response.setHeader("UrlMapping",sb.toString());
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
